<?php
namespace app\admin\controller\customer;

use app\common\model\SystemCustomer;
use library\Controller;
use think\Db;

/**
 * 个人客户
 * Class Customer
 * @package app\admin\controller\customer
 */
class Customer extends Controller
{
     /**
     * 指定数据表
     * @var string
     */
    protected $table = 'SystemCustomer';	
	
    /**
     * 客户列表
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {
        $this->title = '个人客户';
        $where = [];            
		$where[] = ['is_deleted','eq',0];
		$where[] = ['status','eq',1];
		$user_id = intval(session('admin_user.id'));
		if($user_id != '10000'){
			$where[] = ['charger','eq',$user_id];
		}
		$dep_user =  dep_users(1);
		$this->charger_op = assemble_op([''=>'-- 全部负责人 --'], $dep_user);   
		$this->country_op = assemble_op([''=>'-- 全部国家 --'], get_all_options('country'));   
        $this->source_type_op = assemble_op([''=>'-- 全部来源渠道 --'], get_all_options('source_type'));
        $this->post_type_op = assemble_op([''=>'-- 全部客户类型 --'], get_all_options('post_type'));
        $this->intention_level_op = assemble_op([''=>'-- 全部意向程度 --'], SystemCustomer::INTENTION_LEVEL);
			   
		$query = $this->_query($this->table)->like('unique,company_name')->equal('charger,country,source_type,intention_level,post_type');    
		$query->where($where)->order('id desc')->dateBetween('create_at,last_follow_at,first_contact_at')->page();
        
    }
    
    
    /**
     * 列表数据处理
     * @auth true
     * @param array $data
     * @throws \Exception
     */
    protected function _index_page_filter(&$data)
    {
    	$country = get_all_options('country');
    	$source_type = get_all_options('source_type');
    	$post_type = get_all_options('post_type');
    	$intention_level = SystemCustomer::INTENTION_LEVEL;
    	foreach ($data as &$vo) {       	
        	$vo['charger_cn'] = $vo['charger'] ? user_list()[$vo['charger']] : '';
			$vo['source_type_cn'] = $source_type[$vo['source_type']];
			$vo['intention_level_cn'] = $intention_level[$vo['intention_level']];
			$vo['post_type_cn'] = $post_type[$vo['post_type']];
			$vo['country_cn'] = $country[$vo['country']];
        }		
    }
    
    /**
     * 表单数据处理
     * @param array $data
     * @auth true
     */
    protected function _form_filter(array &$data)
    {
        if ($this->request->isPost()) {	
            $where = [['company_name', 'eq', $data['company_name']]];
            if (!empty($data['id'])) $where[] = ['id ', 'neq', $data['id']];
            if (Db::name($this->table)->where($where)->count() > 0) {
                $this->error('公司已存在，请更改公司名称');
            }	
            if($data['wechat']){
            	$where = [['wechat', 'eq', $data['wechat']]];
            	if(!empty($data['id'])){
	            	$where[] = ['id ', 'neq', $data['id']];	            	
	            }
	            if (Db::name($this->table)->where($where)->count() > 0) {
	                $this->error('微信号已存在，请更改微信号');
	            }
            }
            if($data['mobile']){
            	$where = [['mobile', 'eq', $data['mobile']]];
            	if(!empty($data['id'])){
	            	$where[] = ['id ', 'neq', $data['id']];	            	
	            }
	            if (Db::name($this->table)->where($where)->count() > 0) {
	                $this->error('手机号码已存在，请更改手机号码');
	            }
            }
            if($data['whatsapp']){
            	$where = [['whatsapp', 'eq', $data['whatsapp']]];
            	if(!empty($data['id'])){
	            	$where[] = ['id ', 'neq', $data['id']];	            	
	            }
	            if (Db::name($this->table)->where($where)->count() > 0) {
	                $this->error('WhatsApp已存在，请更改WhatsApp');
	            }
            }
            if($data['email']){
            	$where = [['email', 'eq', $data['email']]];
            	if(!empty($data['id'])){
	            	$where[] = ['id ', 'neq', $data['id']];	            	
	            }
	            if (Db::name($this->table)->where($where)->count() > 0) {
	                $this->error('电子邮箱已存在，请更改电子邮箱');
	            }
            }
           		           			  
        }else{       		
        	$this->user_id = intval(session('admin_user.id'));		
        	$this->chargers = dep_users(1); 
        	$this->intention_level = SystemCustomer::INTENTION_LEVEL;
			if(!empty($data['id'])){				
				$this->countrys = get_all_options('country');
				$this->source_types = get_all_options('source_type');
				$this->post_type = get_all_options('post_type');
				$this->transactions = get_all_options('transaction');
			}else{
				$this->countrys = get_normal_options('country');
				$this->source_types = get_normal_options('source_type');
				$this->post_type = get_normal_options('post_type');
				$this->transactions = get_normal_options('transaction');				
			}
        	if($data){
        		$this->oplog = readoplog($data['id'],$this->table);
        	}     	
        }
    }
    

    /**
     * 添加客户
     * @auth true
     */
    public function add()
    {
    	$this->title = '添加客户';
    	$data = [];
    	if($this->request->isPost()){
    		$data = $this->request->post();
    		trim_array($data);
    		
    		$gain_at = date('Y-m-d',time());   		
    		$end_at = get_futuredate(get_customer_config(1,'expire_day'));
    		$create_at = date('Y-m-d H:i:s',time());
    		$data['status'] = 1;
    		
    		$charger = get_charger();
    		
    		$data['charger'] = $data['creater'] = $charger;
    		$data['gain_at'] = $gain_at;
    		$data['end_at'] = $end_at;
    		$data['create_at'] = $data['update_at'] = $create_at;
    		
    	}
    	
        $this->_form($this->table, 'f_form','',[],$data);
    }
    
    
    /**
     * 表单数据后置处理
     * @param number $id
     * @auth true
     */
    protected function _add_form_result($id)
    {
		$info = Db::name($this->table)->where(['id'=>$id])->find();
		if($info){
			$re = Db::name($this->table)->where(['id'=>$id])->update(['unique'=>number_rule_max(16)]);
			if($re){
				save_number_rule_max(16);
			}
			//写入客户转移记录表
			$create_at = date('Y-m-d H:i:s',time());
			$today = date('Y-m-d',time());
			$data = [
				'customer_id' => $info['id'],
				'charger' => $info['charger'],
				'type' => 1,
				'describe'=>'新增客户',
				'add_at' => $today,
				'created_at'=>$create_at,
				'updated_at'=>$create_at,
			];
			Db::name('system_customer_shifts')->insert($data);
			sysoplog('个人客户', '新增'.$info['company_name'].'成功');
			operatelog($info['id'],$this->table,'进行了新增');
			$this->success('保存成功');
		}
    }

    /**
     * 编辑客户
     * @auth true
     */
    public function edit()
    {  	
    	$this->title = '编辑客户';
        $data = [];
    	if($this->request->isPost()){
    		$data = $this->request->post();
    		trim_array($data);
            $update_at = date('Y-m-d H:i:s',time());         
            $data['update_at'] = $update_at;    			
    	}  	
        $this->_form($this->table, 'f_form','',[],$data);
    }
    
    
    /**
     * 表单数据后置处理
     * @param number $id
     * @auth true
     */
    protected function _edit_form_result($id,$data)
    {
		$info = Db::name($this->table)->where(['id'=>$id])->find();
		if($info){
			//更改客户跟进表
			Db::name('system_customer_follows')->where(['customer_id' => $info['id']])->update(['company_name'=>$info['company_name'],'source_type'=>$info['source_type']]);
			sysoplog('个人客户', '编辑'.$info['company_name'].'成功');
			operatelog($info['id'],$this->table,'进行了编辑');
			$this->success('保存成功');	
		}
    }
    
    
       
    /**
     * 查看客户
     * @auth true
     */
    public function browse()
    {  	
    	$this->title = '查看客户'; 	
    	$this->_form($this->table, 'f_browse');   	 	      
    }
    
    
    /**
     * 跟进记录
     * @auth true
     *
     */
    public function followList()
    {
        if ($this->request->isGet()) {
            $parameter = $this->request->get();
            $customer = Db::name($this->table)->where(['id' => $parameter['id']])->find();
            $this->customer_id = $parameter['id'];
            $this->title = '跟进记录  /  ' . $customer['company_name'];		
			$this->source_types = get_all_options('source_type');			
			$this->transactions = get_all_options('transaction');
			$this->users = user_list();
            $this->list = $this->_query('system_customer_follows')->where(['customer_id' => $parameter['id'],'is_deleted'=>0])->order('id desc')->page();
                
            $this->fetch('follow_list');
        }
    }
    
    
    
    /**
     * 添加跟进
     * @auth true
     *
     */
    public function addFollow()
    {
        if ($this->request->isGet()) {
            $parameter = $this->request->get();
            $customer = Db::name($this->table)->where(['id' => $parameter['customer_id'],'is_deleted'=>0,'status'=>1])->field('id,unique,company_name,link_name')->find();
            if(!$customer){
            	$this->error('客户不存在或已进入公海');
            }
            $customer['customer_unique'] = $customer['unique'];
            $this->info = $customer;
            $this->customer_id = $parameter['customer_id'];
//          $this->source_types = get_normal_options('source_type');
            $this->transactions = get_normal_options('transaction');
            
            $this->fetch('follow_form');
        } else {
            $parameter = $this->request->post();
            
            $customer = Db::name($this->table)->where(['id' => $parameter['customer_id'],'is_deleted'=>0,'status'=>1])->field('id,unique,company_name,link_name,source_type,charger,follow_num')->find();
            if(!$customer){
            	$this->error('客户不存在或已进入公海');
            }    
            $user_id = intval(session('admin_user.id'));
			if($user_id != '10000'){
				if($customer['charger'] != $user_id){
					$this->error("不是自己客户，无法添加");
				}
			}
            Db::startTrans();
            try {           	
				$data = [];
	            $data['customer_id'] = $parameter['customer_id'];
	            $data['customer_unique'] = $customer['unique'];
	            $data['company_name'] = $customer['company_name'];
	            $data['link_name'] = $parameter['link_name'];
	            $data['source_type'] = $customer['source_type'];
	            $data['transaction'] = $parameter['transaction'];
	            $data['follow_at'] = $parameter['follow_at'];
	            $data['content'] = $parameter['content'];
	            $data['charger'] = $customer['charger'];
	            $data['creater'] = intval(session('admin_user.id'));
	            $data['created_at'] = $data['updated_at'] = date('Y-m-d H:i:s',time());
	            Db::name('system_customer_follows')->insert($data);
	            
	            //更改客户信息
	            $end_at = get_futuredate(get_customer_config(1,'expire_day'));
	            $follow_num = $customer['follow_num'] + 1;
	            Db::name($this->table)->where(['id' => $parameter['customer_id']])->update(['end_at'=>$end_at,'follow_num'=>$follow_num,'last_follow_at'=>$parameter['follow_at']]);
	            
	            sysoplog('个人客户', '新增'.$customer['company_name'].'跟进记录成功');
				operatelog($customer['id'],$this->table,'添加了一条跟进记录');
                Db::commit();
                
            } catch (Exception $e) {
                Db::rollback();
                $this->error('保存失败，请重试');
            }
            
            $this->success('保存成功');
        }
    }
    
    
    
    /**
     * 编辑跟进
     * @auth true
     *
     */
    public function editFollow()
    {
        if ($this->request->isGet()) {
            $parameter = $this->request->get();
            $follow = Db::name('system_customer_follows')->where(['id' => $parameter['id'],'is_deleted'=>0])->find();
            if(!$follow){
            	$this->error('跟进ID错误');
            } 
            $this->customer_id = $follow['customer_id'];
            $this->source_types = get_all_options('source_type');
            $this->transactions = get_all_options('transaction');
            $this->info = $follow;
            $this->fetch('follow_form');
        } else {
            $parameter = $this->request->post();
            $follow = Db::name('system_customer_follows')->where(['id' => $parameter['id'],'is_deleted'=>0])->find();
            if(!$follow){
            	$this->error('跟进不存在');
            } 
            $customer = Db::name($this->table)->where(['id' => $parameter['customer_id'],'is_deleted'=>0,'status'=>1])->field('id,company_name,link_name,charger,follow_num')->find();
            if(!$customer){
            	$this->error('客户不存在或已进入公海');
            }    
            $user_id = intval(session('admin_user.id'));
			if($user_id != '10000'){
				if($customer['charger'] != $user_id){
					$this->error("不是自己客户，无法编辑");
				}
			}
            Db::startTrans();
            try {           	
				$data = [];
	            $data['link_name'] = $parameter['link_name'];	            
//	            $data['source_type'] = $parameter['source_type'];	
	            $data['transaction'] = $parameter['transaction'];
	            $data['follow_at'] = $parameter['follow_at']; 
	            $data['content'] = $parameter['content'];   
	            $data['updated_at'] = date('Y-m-d H:i:s',time());          
	            Db::name('system_customer_follows')->where(['id'=>$parameter['id']])->update($data);
	            	            
	            //获取客户的最后一条跟进
	            $last_follow = Db::name('system_customer_follows')->where(['customer_id' => $parameter['customer_id'],'is_deleted'=>0])->order('id desc')->find();
	            if($last_follow['id'] == $parameter['id']){
	            	//更改客户信息
//		            $end_at = get_futuredate(get_customer_config(1,'expire_day'));		            
		            Db::name($this->table)->where(['id' => $parameter['customer_id']])->update(['last_follow_at'=>$parameter['follow_at']]);	            	
	            }
	            sysoplog('个人客户', '编辑'.$customer['company_name'].'跟进记录成功');
	            operatelog($customer['id'],$this->table,'编辑了一条跟进记录');         
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error('保存失败，请重试');
            }
            
            $this->success('保存成功');
        }
    }
    
    
    /**
     * 删除跟进
     * @auth true
     */
    public function remove()
    {	
        $id = $this->request->post('id');	
    	$follow = Db::name('system_customer_follows')->where(['id'=>$id,'is_deleted'=>0])->find();
    	if(!$follow){
        	$this->error('跟进不存在');
        }
        $customer = Db::name($this->table)->where(['id' => $follow['customer_id'],'is_deleted'=>0,'status'=>1])->field('id,company_name,charger,follow_num')->find();
        if(!$customer){
        	$this->error('客户不存在或已进入公海');
        }
    	$user_id = intval(session('admin_user.id'));
		if($user_id != '10000'){
			if($customer['charger'] != $user_id){
				$this->error("不是自己客户，无法删除");
			}
		}
		
		Db::startTrans();
        try {           	          
            Db::name('system_customer_follows')->where(['id'=>$id])->update(['is_deleted'=>1]);
            //获取客户的最后一条跟进
            $last_follow = Db::name('system_customer_follows')->where(['customer_id' => $follow['customer_id'],'is_deleted'=>0])->order('id desc')->find();
            $last_follow_at = $last_follow ? $last_follow['follow_at'] : '';
            $follow_num = $customer['follow_num'] - 1;
            Db::name($this->table)->where(['id' => $follow['customer_id']])->update(['last_follow_at'=>$last_follow_at,'follow_num'=>$follow_num]);	            		         
            sysoplog('个人客户', '删除'.$customer['company_name'].'跟进记录成功');  
            operatelog($customer['id'],$this->table,'删除了一条跟进记录');          	
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error('删除失败，请重试');
        }
		
		$this->success('删除成功');
    }
    
    
   
	
	
    
    /**
     * 导出公司
     * @auth true
     */
//  public function export()
//  {  	
//  	$data = $this->request->param();
//  	$ids = explode(',', $data['id']);
//  	$list = CompanyService::export_company($ids);
//  	toexcel($list['filename'],$list['titles'],$list['list']);   	 	      
//  }
    

}
